/*
 * @Description:
 * @Author: chenjiaxin
 * @Date: 2022-02-26 18:57:27
 * @LastEditTime: 2022-02-27 13:53:53
 * @FilePath: \nitem\test\test.js
 */
import Nitem from "../index.js";
let nitem = new Nitem();

// console.log(nitem);
function fn(res) {
  console.log("fn函数", res);
}
// console.log("1=监听abc", res, this)
nitem.on(
  "abc",
  function (res) {
    console.log("1=监听abc", res, this);
  },
  { name: "cjx" }
);
nitem.on("abc", function (res) {
  console.log("2=监听abc", res, this);
});
nitem.on("abc", fn);

nitem.emit("abc", [1, 2, 3]);
nitem.off("abc", fn);
nitem.emit("abc", "res");

/**
 * 节流函数  测试换行
 * @param {*} fn
 * @param {*} interval
 * @param {*} options
 * @returns
 */
const throttle = (fn, interval = 1000, options = { leading: true, traling: false, callbackFn: null }) => {
  let lastTime = 0;
  let { leading, traling, callbackFn } = options;
  let timeId = null;
  function newThrottle(...args) {
    let rowTime = new Date().getTime();
    if (!leading && !lastTime) {
      //不要第一次触发 并且 lastTime 为false 的时候，把 lastTime 赋值 为 当前时间。这样第一次就不会触发了
      lastTime = rowTime;
    }
    // 执行条件 rowTime - lastTime >= interval 就是要去执行 触发函数
    let spaceTime = interval - (rowTime - lastTime);
    if (spaceTime <= 0) {
      //要执行
      // fn();
      fn.apply(this, args);
      lastTime = rowTime;
      if (typeof callbackFn === "function") callbackFn("执行参数");
      return;
    }
    //时间还没有到
    if (traling) {
      if (timeId) clearTimeout(timeId);
      timeId = setTimeout(() => {
        // fn();
        fn.apply(this, args);
        lastTime = new Date().getTime();
        timeId = null;
        if (typeof callbackFn === "function") callbackFn("执行参数");
      }, spaceTime);
    }
  }
  //取消功能
  newThrottle.cancle = function () {
    if (timeId) clearTimeout(timeId);
  };
  return newThrottle;
};
